package com.itheima.demo;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

/**
 * 创建index索引库
 * @作者 itcast
 * @创建日期 2021/4/2 8:54
 **/
public class EsDemo05 {

    RestHighLevelClient client;

    /**
     * 初始化es 客户端
     */
    @Before
    public void init(){
        client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.200.150", 9200, "http"),
                        new HttpHost("192.168.200.151", 9200, "http"),
                        new HttpHost("192.168.200.152", 9200, "http")
                )
        );
    }


    /**
     * 创建索引库
     */
    @Test
    public void createIndex() throws IOException {
//        1. 创建 对应的 请求对象  CreateIndexRequest
        CreateIndexRequest request = new CreateIndexRequest("cluster-demo");// 索引库名称
//        1.1 设置setting信息
        // 参数1: setting的json字符串信息  参数2: 指定内容类型为json
        request.settings("{\n" +
                "    \"number_of_shards\": 3,\n" +
                "    \"number_of_replicas\": 1\n" +
                "  }", XContentType.JSON);
//        2. 使用客户端执行对应的请求方法  client.indices().create(request);
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
//        3. 解析响应结果
        System.out.println(response.isAcknowledged());
    }

    /**
     * 判断索引库是否存在
     */
    @Test
    public void isHas() throws IOException {
        // 1. 创建 XXXX请求
        GetIndexRequest request = new GetIndexRequest("user");
        // 2. 执行 XXX请求方法
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        // 3. 得到响应结果
        System.out.println(exists);
    }
    /**
     * 关闭es 客户端
     */
    @After
    public void close(){
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
